home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2213 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  979 b 

  1. Path: unix.sri.com!usenet
  2. From: mklenk@updike.sri.com (Mark Klenk)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: 19 Jan 1996 21:33:44 GMT
  6. Organization: SRI International
  7. Message-ID: <4dp2no$3va@unix.sri.com>
  8. References: <4dorr8$i58@cloner3.netcom.com>
  9. Reply-To: mklenk@updike.sri.com
  10. NNTP-Posting-Host: 204.75.161.40
  11.  
  12.  
  13. Andrew Snyder wrote:
  14. >
  15. > Bill Simpson wrote:
  16. >>
  17. >>Is there a fast way to decide whether a number n is a power of 2?
  18. >
  19. >no tricks
  20. >
  21. >#define ISPOW2(x) (((x) & 1) ^ 1)
  22.  
  23.     He asked for POWER of 2, not MULTIPLE.
  24.  
  25.     Your macro will return non-zero for 6, for example,
  26.     which is not a power of 2.
  27.  
  28.     I don't think there is any way to do it other than
  29.     recursively or iteratively.
  30.  
  31. int
  32. NumIsPowerOf2(int num)
  33. {
  34.     if (num <= 0) {
  35.         return 0;
  36.     }
  37.  
  38.     while (num > 0) {
  39.         if ((num & 1) && num > 1) {
  40.             return 0;
  41.         }
  42.         num >>= 1;
  43.     }
  44.  
  45.     return 1;
  46. }
  47.  
  48. ---
  49.  
  50. mklenk@coronacorp.com       (Mark Klenk)
  51.  
  52.  
  53.  
  54.